<?php


class cache extends mysql
{
	var $path		= 'data/heap/';
	var $sql		= '';
	var $get		= 'getAll';
	var $live		= 3600;

	function cache()
	{
		$this->conn();
	}

	function uncache($sql)
	{
		$getBy=$this->get;
		$data=$this->query($sql)->getAll();
		return $data;
	}
	
	function getData($sql)
	{
		if(!is_file($this->file($sql)))
		{
			return $this->setData($sql);
		}
		$data=$this->decryption(file_get_contents($this->file($sql)));
		if($data['expire']>=time())
		{
			$return=$this->setData($sql);
			if(is_array($return))
			{
				return $return;
			}
			else
			{
				return $this->uncache($this->sql);
			}
		}
		else
		{
			return $data['heap'];
		}
	}

	function setData($sql,$expire='')
	{
		$data=$this->uncache($sql);
		if(is_array($data)){
			$encryption=$this->encryption($data,$expire);
			file_put_contents($this->file($sql), $encryption);
			return $data;
		}else{
			return false;
		}
	}

	private function encryption($data,$expire='')
	{
		$expire=$expire?$expire:time()+$this->live;
		return '<?php exit;?>' . $expire .serialize($data);
	}
	
	private function decryption($data)
	{
		$return['expire'] 		= substr($data, 13, 10);
        $return['heap']     	= unserialize(substr($data, 23));
        return $return;
	}
	
	private function file($sql)
	{
		return $this->path.md5($sql).".php";
	}

}